package com.xxxx.server.config.security.compoent;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 权限控制
 * 判断用户角色
 */
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    /**
     * Collection<ConfigAttribute>对应的是一个集合
     * @param authentication
     * @param o
     * @param configAttributes
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            if (authentication == null) {
                throw new AccessDeniedException("当前访问没有权限");
            }
            // 当前url所需要的role
            String needRole = configAttribute.getAttribute();
            // 判断角色是否为登录即 可访问的角色，此角色在CustomFilter中设置
            if("ROLE_LOGIN".equals(needRole)){
                // 判断是否登陆
                if (authentication instanceof AnonymousAuthenticationToken){
                    //如果是，就表示没有登录抛出异常
                    throw new AccessDeniedException("CustomUrlDecisionManager中的尚未登录，请登录！");
                }else {
                    return;
                }
            }
            // 判断用户角色是否为url所需角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            // 获取权限后遍历
            for (GrantedAuthority authority : authorities ) {
                // 判断此权限是否和needRole权限一致
                if(authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw  new AccessDeniedException("CustomUrlDecisionManager中的权限不足，请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
